<template>
  <div>
    <el-form
      :model="addForm"
      ref="addFormRef"
      label-position="top"
      :rules="rules"
    >
      <el-form-item
        v-for="item in labelList"
        :key="item.id"
        :label="item.specsName"
        :prop="item.specsName"
      >
        <el-select
          v-model="addForm[item.specsName]"
          filterable
          :placeholder="`请选择${item.specsName}`"
        >
          <el-option
            v-for="item2 in item.list"
            :key="item2.id"
            :label="item2.specsValueName"
            :value="item2.specsValueName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="价格" prop="goodsPrice">
        <el-input-number
          v-model="addForm.goodsPrice"
          :min="0.01"
          :step="0.01"
          placeholder="请输入价格"
          class="w-full"
          :precision="2"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { add, cloneDeep } from "lodash";
import Decimal from "decimal.js";
import { handleApiResponse } from "@/utils/request.js";
import {
  AddGoodsSpec,
  UpdateGoodsSpec,
} from "../../../../../wailsjs/go/api/GoodsApi.js";

onMounted(() => {
  if (props.labelList?.length > 0) {
    props.labelList.forEach((item) => {
      rules.value[item.specsName] = [
        {
          required: true,
          message: `请选择${item.specsName}`,
          validator: (rule, value, callback) => {
            if (!validationEnabled.value) {
              callback(); // 如果验证未启用，直接通过
            } else if (!value) {
              callback(new Error(`请选择${item.specsName}`));
            } else {
              callback();
            }
          },
        },
      ];
    });
  }

  if (props.specId != 0) {
    addForm.value = props.spec_detailForm;
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  specId: {
    type: Number,
    default: null,
  },
  detailForm: {
    type: Object,
    default: () => ({}),
  },
  spec_detailForm: {
    type: Object,
    default: () => ({}),
  },
  labelList: {
    type: Array,
    default: () => [],
  },
});

const addFormRef = ref(null);
const addForm = ref({});

const handleSubmit = () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    // emit("handleBack", 1);

    let form = cloneDeep(addForm.value);
    form.goodsPrice = Decimal(form.goodsPrice).mul(100).toString();
    form.goodsPrice = +form.goodsPrice;
    let specsList = [];
    props.labelList.forEach((item) => {
      item.list.forEach((child) => {
        for (const key in addForm.value) {
          if (addForm.value[key] == child.specsValueName) {
            specsList.push({
              id: item.id,
              specsName: item.specsName,
              list: [
                {
                  id: child.id,
                  specsValueName: child.specsValueName,
                },
              ],
            });
          }
        }
      });
    });

    if (props.specId == 0) {
      handleApiResponse(() =>
        AddGoodsSpec({
          goodsPrice: form.goodsPrice,
          goodsId: props.detailForm.id,
          specsList: specsList,
        })
      ).then((res) => {
        if (res.code == 0) {
          ElMessage.success("新增成功");
          emit("handleBack");
        }
      });
    } else {
      handleApiResponse(() =>
        UpdateGoodsSpec({
          id: addForm.value.id,
          goodsPrice: form.goodsPrice,
          goodsId: props.detailForm.id,
          specsList: specsList,
        })
      ).then((res) => {
        if (res.code == 0) {
          ElMessage.success("修改成功");
          emit("handleBack");
        }
      });
    }
  });
};

const validationEnabled = ref(false); // 添加一个标志来控制验证
const rules = ref({
  goodsPrice: [
    {
      required: true,
      message: "请输入价格",
      validator: (rule, value, callback) => {
        if (!validationEnabled.value) {
          callback(); // 如果验证未启用，直接通过
        } else if (!value) {
          callback(new Error(`请选择${item.specsName}`));
        } else {
          callback();
        }
      },
    },
  ],
});

defineExpose({
  handleSubmit,
});
</script>

<style scoped lang="scss">
</style>